package www.bplead.com.controller.action;

import android.content.Context;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.util.Log;
/**
 * Created by wangyangzi on 2016/9/4.
 */
public class BaseNetAction extends BaseAction{
    private static final String TAG = "BaseNetAction";
    protected static RequestQueue mQueue = null;
    protected static Context mContext;

    public BaseNetAction(Context context) {
        mContext = context;
        if(mQueue == null) {
            mQueue = Volley.newRequestQueue(context);
        }
    }

    /************************************** 接口数据上传与接收(String) **************************************/
    public static class NtStringRequest extends StringRequest{
        private static final int SOCKET_TIMEOUT = 10 * 1000;

        public NtStringRequest(int method,String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
            super(method, url, listener, errorListener);
            this.setRetryPolicy(new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        }

        /*@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return provideHeaders();
        }*/
    }

    protected static Map<String, String> provideHeaders() {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/text");
        headers.put("Content-Type","application/text");
        headers.put("charset", "UTF-8");
        headers.put("Accept-Charset", "UTF-8");
        /*Log.v(TAG,"getToken " + AccountManager.getToken(mContext));
        headers.put("twx-mobile-token", AccountManager.getToken(mContext));*/
        return headers;
    }

    /************************************** 接口数据上传与接收(Json) **************************************/
    public static class DxJsonObjectRequest extends JsonObjectRequest {
        private static final int SOCKET_TIMEOUT = 10 * 1000;

        public DxJsonObjectRequest(int method, String url, JSONObject jsonRequest,
                                   Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
            super(method, url, jsonRequest, listener, errorListener);
            this.setRetryPolicy(new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        }

        public DxJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
            super(url, jsonRequest, listener, errorListener);
            this.setRetryPolicy(new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        }
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");
            headers.put("appKey", "9f73192b-0957-4413-b2f1-6a8a371520ef");
            return headers;
        }
    }

    /************************************** 接口数据上传与接收(File) **************************************/
    public static class MultipartRequest extends Request<String> {
        private static final int SOCKET_TIMEOUT = 10 * 1000;
        private MultipartEntity entity = new MultipartEntity();

        private  Response.Listener<String> mListener;

        private List<File> mFileParts;
        private String mFilePartName;
        private Map<String, String> mParams;

        /**
         * 单个文件＋参数 上传
         * @param url
         * @param listener
         * @param errorListener
         * @param filePartName
         * @param file
         * @param params
         */
        public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener,
                                String filePartName, File file, Map<String, String> params){
            super(Method.POST, url, errorListener);
            mFileParts = new ArrayList<File>();
            if(file != null && file.exists()){
                mFileParts.add(file);
            }else{
                VolleyLog.e("MultipartRequest---file not found");
            }
            mFilePartName = filePartName;
            mListener = listener;
            mParams = params;
            buildMultipartEntity();
        }

        /**
         * 多个文件＋参数上传
         * @param url
         * @param listener
         * @param errorListener
         * @param filePartName
         * @param files
         * @param params
         */
        public MultipartRequest(String url,Response.Listener<String> listener,Response.ErrorListener errorListener
                , String filePartName,List<File> files, Map<String, String> params) {
            super(Method.POST, url, errorListener);
            mFilePartName = filePartName;
            mListener = listener;
            mFileParts = files;
            mParams = params;
            buildMultipartEntity();
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String parsed;
            try {
                parsed = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
            } catch (UnsupportedEncodingException e) {
                parsed = new String(response.data);
            }
            return Response.success(parsed,
                    HttpHeaderParser.parseCacheHeaders(response));
        }

        @Override
        protected void deliverResponse(String response) {
            mListener.onResponse(response);
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = super.getHeaders();

            if (headers == null || headers.equals(Collections.emptyMap())) {
                headers = new HashMap<String, String>();
            }

            headers.put("Accept","application/json");
            headers.put("Content-Type","application/json");
            headers.put("appKey","9f73192b-0957-4413-b2f1-6a8a371520ef");

            return headers;
        }

        @Override
        public String getBodyContentType() {
            return entity.getContentType().getValue();
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try{
                entity.writeTo(bos);
            } catch (IOException e) {
                VolleyLog.e("IOException writing to ByteArrayOutputStream");
            }
            return bos.toByteArray();
        }

        private void buildMultipartEntity() {
            if (mFileParts != null && mFileParts.size() > 0) {
                for (File file : mFileParts) {
                    entity.addPart(mFilePartName, new FileBody(file));
                }

                long l = entity.getContentLength();
                Log.i("YanZi-volley", mFileParts.size() + "个，长度：" + l);
            }


            try {
                if (mParams != null && mParams.size() > 0) {
                    for (Map.Entry<String, String> entry : mParams.entrySet()) {
                        entity.addPart(entry.getKey(),new StringBody(entry.getValue(), Charset.forName("UTF-8")));
                    }
                }
            } catch (UnsupportedEncodingException e) {
                VolleyLog.e("UnsupportedEncodingException");
            }
        }


    }
}
